#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/22  13:49
# @Author: 余浪人
# @email: yulangren520@gmail.com

import requests, time, re, json, base64
from flask import request, render_template, jsonify, redirect, url_for, current_app
from flask_login import login_required, login_user, current_user, logout_user
from apps.control import sys_bp
from apps.lib.user_login import parse_quote, createCookie, get_token
from apps.forms.member_form import TL_Member_Form, TL_Login_Form, TL_Member_Edit_Form
from apps.models.member_model import TL_Member_Model, db
from apps.lib.public import add_data, real_delete_data, check_obj, edit_data, check_password, errors, real_deletes, page_auto, redis_, create_hash
@sys_bp .route ('/member_list',endpoint ='member_list',methods =['GET','DELETE','DELETES'])
@login_required
def member_list ():
    if request .method =='DELETE':
        OOO00O0000O0000OO =request .form .get ('uid')
        OO0OOOOOO000O0000 =TL_Member_Model .query .filter_by (id =OOO00O0000O0000OO ).first ()
        if not check_obj (OO0OOOOOO000O0000 ):
            if OO0OOOOOO000O0000 .id !=1 :
                return real_delete_data (TL_Member_Model ,db ,OOO00O0000O0000OO )
            return jsonify ({"status":1 ,"msg":"超级管理员不可删除!"})
    elif request .method =='DELETES':
        return real_deletes (TL_Member_Model ,db ,request .form .get ('id_array').split ('#TL#'))
    O00OOO0OO00OO000O ,OOOOO0O00O00OO0O0 =page_auto (TL_Member_Model .query .order_by (TL_Member_Model .id .desc ()))
    return render_template ('system_template/member_list.html',data_list =O00OOO0OO00OO000O ,page =OOOOO0O00O00OO0O0 )
@sys_bp .route ('/member_add',endpoint ='member_add',methods =['GET','POST'])
@login_required
def member_add ():
    if request .method =='POST':
        return add_data (TL_Member_Model ,TL_Member_Form ,db )
    return render_template ('system_template/member.html',form =TL_Member_Form (request .form ))
@sys_bp .route ('/member_edit',endpoint ='member_edit',methods =['GET','POST'])
@login_required
def member_edit ():
    O000000000OOOOOOO =TL_Member_Model .query .filter_by (id =current_user .id ).first ()
    if request .method =='POST'and not check_obj (O000000000OOOOOOO ):
        return edit_data (TL_Member_Edit_Form ,TL_Member_Model ,db ,current_user .id )
    if not check_obj (O000000000OOOOOOO ):
        return render_template ('system_template/member.html',form =TL_Member_Edit_Form (data =dict (O000000000OOOOOOO )))
@sys_bp .route ('/bind_code',endpoint ='bind_code',methods =['GET'])
@login_required
def bind_code ():
    O0OOO0OO00O000OO0 =redis_ (db =0 )
    O00O000O0000O00O0 =O0OOO0OO00O000OO0 .get (str (request .remote_addr ))
    if O00O000O0000O00O0 :
        O0OO0O00O00O00O0O =json .loads (O00O000O0000O00O0 )
        OO0O0O0O00OO0OO0O ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36','Cookie':createCookie (O0OO0O00O00O00O0O )}
        O00O0O0O000OO0000 =parse_quote ('https://graph.qq.com/oauth2.0/login_jump')
        OOOO00OOOOOOOO0O0 =get_token (O0OO0O00O00O00O0O ["qrsig"])
        O0O00OO0O0OOOO00O =int (time .time ()*1000 )
        O0OOO0OO0OOO0O000 =current_app .config .get ('APP_ID')
        O00O000OO0O00O000 =O0OO0O00O00O00O0O ["pt_login_sig"]
        O0O0O000O00O00OOO =f"https://ssl.ptlogin2.qq.com/ptqrlogin?u1={O00O0O0O000OO0000}&ptqrtoken={OOOO00OOOOOOOO0O0}&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-{O0O00OO0O0OOOO00O}&js_ver=19091015&js_type=1&login_sig={O00O000OO0O00O000}&pt_uistyle=40&aid=716027609&daid=377&pt_3rd_aid={O0OOO0OO0OOO0O000}&"
        O0O00OO0O0O0OOO00 =requests .get (O0O0O000O00O00OOO ,headers =OO0O0O0O00OO0OO0O )
        OOO0OO000O0OO0OOO =eval (O0O00OO0O0O0OOO00 .text .replace ('ptuiCB',''))
        if OOO0OO000O0OO0OOO [0 ]=='0'and '登录成功'in OOO0OO000O0OO0OOO [-2 ]:
            OO0O000OOOO000OO0 =requests .utils .dict_from_cookiejar (O0O00OO0O0O0OOO00 .cookies )
            OOOOO00OO0O0O0O0O ,O00O0OOO0O00OOO00 =OO0O000OOOO000OO0 ['skey'],create_hash (OO0O000OOOO000OO0 ['uin'])
            O0O0O0O0OOOO00OO0 =TL_Member_Model .query .filter_by (uuid =current_user .uuid ).first ()
            if not check_obj (O0O0O0O0OOOO00OO0 )and O0O0O0O0OOOO00OO0 :
                try :
                    O0O0O0O0OOOO00OO0 .set_attrs ({'user_rk':O00O0OOO0O00OOO00 })
                    db .session .commit ()
                    O0OOO0OO00O000OO0 .delete (str (request .remote_addr ))
                    return jsonify ({'status':0 ,'msg':'绑定成功'})
                except :
                    db .session .rollback ()
            return jsonify ({'status':4 ,'msg':'绑定失败'})
        elif OOO0OO000O0OO0OOO [0 ]=='66':
            return jsonify ({'status':2 ,'msg':'二维码未失效'})
        elif OOO0OO000O0OO0OOO [0 ]=='67':
            return jsonify ({'status':3 ,'msg':'二维码认证中'})
    return jsonify({'status':1 ,'msg':'请重新后去二维码！'})
@sys_bp .route ('/bind_account_html',endpoint ='bind_account_html',methods =['GET'])
@login_required
def bind_account_html ():
    return render_template ('system_template/account_bind.html')
@sys_bp .route ('/admin',endpoint ='member_login',methods =['GET','POST'])
def member_login ():
    OO0O00O0O0000O0OO =TL_Login_Form (request .form )
    if request .method =='POST':
        O000OO0O000OO000O =request .form .get ('username').strip ()
        O0OOO00O000OOO0O0 =request .form .get ('password')
        if OO0O00O0O0000O0OO .validate ()and O000OO0O000OO000O and O0OOO00O000OOO0O0 :
            OO0O00O000OOOO0OO =TL_Member_Model .query .filter_by (username =O000OO0O000OO000O ).first ()
            if not check_obj (OO0O00O000OOOO0OO )and OO0O00O000OOOO0OO :
                login_user (OO0O00O000OOOO0OO )
                if check_password (OO0O00O000OOOO0OO .password ,O0OOO00O000OOO0O0 ):
                    return jsonify ({"status":0 ,"msg":"登录成功!"})
                return jsonify ({"status":1 ,"msg":"用户密码错误!"})
        return jsonify ({"status":1 ,"msg":errors (OO0O00O0O0000O0OO )})
    return render_template ('system_template/login.html')
@sys_bp .route ('/logout',endpoint ='logout',methods =['GET'])
@login_required
def logout ():
    logout_user ()
    return redirect (url_for ('sys_bp.member_login'))
@sys_bp .route ('/qqCode',endpoint ='qqCode',methods =['GET'])
def get_Vcode ():
    OOOO0OO0O000O0O00 =requests .session ()
    OO0O00000O0OO00O0 =int (time .time ()*1000 )
    O00OOO0O00O0OO000 =current_app .config .get ('APP_ID')
    OO0OOO00O000OOO00 =current_app .config .get ('REDIRECT_URI').split ('/')[2 ]
    O0OOOO00OO000O0O0 =parse_quote (current_app .config .get ('REDIRECT_URI'))
    O0OOO0OO0OO0OOOO0 =f'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={O00OOO0O00O0OO000}&redirect_uri={O0OOOO00OO000O0O0}&state=login'
    try :
        O0O00OOO0O000OO00 ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}
        O0O0OOO0OO00000OO =OOOO0OO0O000O0O00 .get (O0OOO0OO0OO0OOOO0 ,headers =O0O00OOO0O000OO00 )
        O0OOOO000O0OOOOO0 =re .findall ('appid=(\d+)&daid=(\d+)&style',O0O0OOO0OO00000OO .text )[0 ]
        OO00OO0OO0OO0OOOO ,OOOO0OO00O0O0OOO0 =O0OOOO000O0OOOOO0 [0 ],O0OOOO000O0OOOOO0 [-1 ]
        OOO00OOO0OO00000O =f'https://ssl.ptlogin2.qq.com/ptqrshow?appid={OO00OO0OO0OO0OOOO}&e=2&l=M&s=3&d=72&v=4&t={OO0O00000O0OO00O0}&daid={OOOO0OO00O0O0OOO0}&pt_3rd_aid={O00OOO0O00O0OO000}'
        OO0OO0000OOO000OO =OOOO0OO0O000O0O00 .get (OOO00OOO0OO00000O )
        OO000O00O0OO000O0 =requests .utils .dict_from_cookiejar (OO0OO0000OOO000OO .cookies )
        O0OO0OO000O0OOO00 =f'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=716027609&daid=383&style=33&login_text=授权并登录&hide_title_bar=1&hide_border=1&target=self&s_url=https://graph.qq.com/oauth2.0/login_jump&pt_3rd_aid={O00OOO0O00O0OO000}&pt_feedback_link=https://support.qq.com/products/77942?customInfo={OO0OOO00O000OOO00}.appid{O00OOO0O00O0OO000}'
        O0O0OOO00000O0000 =OOOO0OO0O000O0O00 .get (O0OO0OO000O0OOO00 )
        OO000O00O0OO000O0 .update (requests .utils .dict_from_cookiejar (O0O0OOO00000O0000 .cookies ))
        O0O000OOOO000O000 =redis_ (db =0 )
        O0O000OOOO000O000 .set (str (request .remote_addr ),json .dumps (OO000O00O0OO000O0 ),10 *60 )
        OOOO000OOOOOOO00O =base64 .b64encode (OO0OO0000OOO000OO .content ).decode ('utf-8')
        O0OOOOO000O00OO0O ='data:image/jpg;base64,'+OOOO000OOOOOOO00O
        return jsonify ({'status':0 ,'msg':'success','data':O0OOOOO000O00OO0O })
    except :
        return jsonify ({'status':4 ,'msg':'error'})
@sys_bp .route ('/verify_user',endpoint ='verify_user',methods =['GET'])
def verify_user ():
    O00O000OO00000OO0 =redis_ (db =0 )
    O0OOO0000O000OOOO =O00O000OO00000OO0 .get (str (request .remote_addr ))
    if O0OOO0000O000OOOO :
        O000OOOOOO0OO0O0O =json .loads (O0OOO0000O000OOOO )
        OOO000OOOOOO00O0O ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36','Cookie':createCookie (O000OOOOOO0OO0O0O )}
        O0O0000OOOO0O00O0 =parse_quote ('https://graph.qq.com/oauth2.0/login_jump')
        OO00000O0O000OOOO =get_token (O000OOOOOO0OO0O0O ["qrsig"])
        OOO0O0000O0O0OO0O =int (time .time ()*1000 )
        O000OOOO000000000 =current_app .config .get ('APP_ID')
        OO00OOOOO0OO000O0 =O000OOOOOO0OO0O0O ["pt_login_sig"]
        O000OO00O0O0OOO00 =f"https://ssl.ptlogin2.qq.com/ptqrlogin?u1={O0O0000OOOO0O00O0}&ptqrtoken={OO00000O0O000OOOO}&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-{OOO0O0000O0O0OO0O}&js_ver=19091015&js_type=1&login_sig={OO00OOOOO0OO000O0}&pt_uistyle=40&aid=716027609&daid=377&pt_3rd_aid={O000OOOO000000000}&"
        OOO0OO000OOOO0O0O =requests .get (O000OO00O0O0OOO00 ,headers =OOO000OOOOOO00O0O )
        O00O00000O00OOOOO =eval (OOO0OO000OOOO0O0O .text .replace ('ptuiCB',''))
        if O00O00000O00OOOOO [0 ]=='0'and '登录成功'in O00O00000O00OOOOO [-2 ]:
            O0O0O000OOO000O00 =requests .utils .dict_from_cookiejar (OOO0OO000OOOO0O0O .cookies )
            O0O00O0O0O0OOOO00 ,OOOO00O00OOOO0OOO =O0O0O000OOO000O00 ['skey'],create_hash (O0O0O000OOO000O00 ['uin'])
            O00OO00O0OO0O0OO0 =TL_Member_Model .query .filter (TL_Member_Model .user_rk ==OOOO00O00OOOO0OOO ,TL_Member_Model .status ==1 ).first ()
            if O00OO00O0OO0O0OO0 :
                login_user (O00OO00O0OO0O0OO0 )
                O00O000OO00000OO0 .delete (str (request .remote_addr ))
                return jsonify ({'status':0 ,'msg':'登录成功！','location':url_for ('sys_bp.base_frame')})
            return jsonify ({'status':4 ,'msg':'拒绝，没有权限！'})
        elif O00O00000O00OOOOO [0 ]=='66':
            return jsonify ({'status':2 ,'msg':'二维码未失效'})
        elif O00O00000O00OOOOO [0 ]=='67':
            return jsonify ({'status':3 ,'msg':'二维码认证中'})
    return jsonify ({'status':1 ,'msg':'请重新后去二维码！'})
